<script setup>
import { ref, reactive, onMounted } from "vue";
import {
  adminPage,
  adminDeleteByUserId,
  adminDeleteBatch,
  adminAdd,
  adminEdit,
} from "@/apis/admin/user";
import { Delete, Edit, Plus } from "@element-plus/icons-vue";
// 存储表格数据的变量
const tableData = ref([]);
// 搜索输入框搜索条件
const search = reactive({
  username: "",
  nickname: "",
  phone: "",
  email: "",
});

/**
 * 搜索输入框对应的触发事件
 * @param {String} value 输入框值
 */

const onSearchChange = () => {
  getPage();
};

// 过滤对应的条件
const filter = reactive({
  gender: null,
  status: null,
});

/**
 * 搜索输入框对应的触发事件
 * @param {String} value 下拉框值
 */

const onFilterChange = () => {
  getPage();
};
// 过滤对应的选项
const filterOptions = reactive({
  gender: [
    {
      label: "男",
      value: "M",
    },
    {
      label: "女",
      value: "F",
    },
  ],
  status: [
    {
      label: "启用",
      value: 1,
    },
    {
      label: "禁用",
      value: 0,
    },
  ],
});

// 存储排序字段
const orders = reactive({
  column: "id",
  isAsc: true,
});
/**
 * 表格排序函数
 * @param {*} column 当前列对
 * @param {*} prop 当前字段
 * @param {*} order 当前排序方式
 */
const sortChange = ({ prop, order }) => {
  console.log(prop, order);

  Object.assign(orders, {
    column: `CAST(${prop} AS UNSIGNED)`,
    isAsc: order === "ascending",
  });
  getPage();
};

/**
 * 删除一行
 * @param {*} scope
 */
const deleteRow = (scope) => {
  console.log(scope);
  adminDeleteByUserId(scope.row.id).then((result) => {
    // console.log(result);
    getPage();
  });
};

/**
 * 获取表格组件引用对象： 前提在表格上加上 ref="tableRef"

 */
const tableRef = ref();
/**
 * 删除全部选中行
 */
const deleteAll = async () => {
  const selectionRows = tableRef.value.getSelectionRows();
  // console.log(selectionRows);
  const ids = selectionRows.map((row) => {
    return row.id;
  });

  await adminDeleteBatch(ids).then((result) => {
    // console.log(result);
  });
  getPage();
  // console.log(ids)
};

/**
 * 分页查询
 * @param {*} filter 过滤
 * @param {*} search 搜索
 * @param {*} orders 排序
 */
const getPage = () => {
  adminPage(
    {
      filter: filter,
      search: search,
      orders: [orders],
    },
    pagination.page,
    pagination.size
  ).then((result) => {
    // console.log(result);
    tableData.value = result.data.records;
    pagination.total = result.data.total;
  });
  // .catch(err => {
  //   console.log("###########");
  // })
};

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0,
});
/**
 * 分页改变函数
 * @param {*} currentPage 当前页
 * @param {*} pageSize 每页条数
 */

const onPaginationChange = (currentPage, pageSize) => {
  pagination.page = currentPage;
  pagination.size = pageSize;
  getPage();
};

/**
 * 添加和修改表格数据
 */
const plusAndEditForm = ref({});

/**
 * 添加和修改的对话框
 */
const plusAndEditDialog = reactive({
  isVisible: false,
  title: "",
});

/**
 * 修改当前行的数据
 * @param {*} scope
 */

const editRow = (scope) => {
  plusAndEditDialog.isVisible = true;
  plusAndEditDialog.title = "修改";
  // console.log(scope);
  Object.assign(plusAndEditForm.value, scope.row);
  // console.log(plusAndEditForm.value)
};

/**
 * 添加一行数据
 */
const plusRow = () => {
  plusAndEditDialog.isVisible = true;
  plusAndEditDialog.title = "添加";
  plusAndEditForm.value = {};
  plusAndEditForm.value.status = true;
};
/**
 * 修改和添加的保存功能
 */
const save = async () => {
  plusAndEditDialog.isVisible = false;

  // console.log(plusAndEditDialog);

  if (plusAndEditDialog.title == "添加") {
    await adminAdd(plusAndEditForm.value).then(() => {});
  } else if (plusAndEditDialog.title == "修改" && plusAndEditForm.value.id) {
    await adminEdit(plusAndEditForm.value).then(() => {
      // console.log(plusAndEditForm.value);
    });
  }
  getPage();
  // console.log(plusAndEditForm);
};

// 触发状态开关
const switchChange = async (row) => {
  // console.log(row);
  try {
    await adminEdit(row);
    getPage();
  } catch (error) {
    console.error(error);
  }
};

// 生命周期
onMounted(() => {
  // 页面加载的时候立刻执行一次请求
  getPage();
});
</script>

<template>
  <div class="toolbar">
    <el-input
      v-model="search.username"
      placeholder="请输入用户名"
      clearable
      @change="onSearchChange"
    />
    <el-input
      v-model="search.nickname"
      placeholder="请输入搜索昵称"
      clearable
      @change="onSearchChange"
    />
    <el-input
      v-model="search.mobile"
      placeholder="请输入搜索电话号码"
      clearable
      @change="onSearchChange"
    />
    <el-input
      v-model="search.email"
      placeholder="请输入搜索邮箱"
      clearable
      @change="onSearchChange"
    />
  </div>

  <div class="filter">
    <el-select
      v-model="filter.gender"
      placeholder="请选择性别"
      clearable
      @change="onFilterChange"
    >
      <el-option
        v-for="item in filterOptions.gender"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>

    <el-select
      v-model="filter.status"
      placeholder="请选择状态"
      clearable
      @change="onFilterChange"
    >
      <el-option
        v-for="item in filterOptions.status"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
  </div>
  <div class="btn-group">
    <el-button-group>
      <el-button type="primary" :icon="Plus" @click="plusRow">添加</el-button>
      <el-button type="danger" :icon="Delete" @click="deleteAll"
        >删除全部</el-button
      >
    </el-button-group>
  </div>

  <el-table
    ref="tableRef"
    :data="tableData"
    @sort-change="sortChange"
    tooltip-effect="light"
    :show-overflow-tooltip="true"
  >
    <el-table-column type="selection" width="120px" />
    <el-table-column prop="role" label="角色" sortable fixed width="120px" />
    <el-table-column prop="username" label="用户名" sortable width="120px" />
    <el-table-column prop="nickname" label="昵称" sortable />
    <el-table-column prop="gender" label="性别" sortable width="120px">
      <template #default="scope">
        {{ scope.row.gender === "F" ? "女" : "男" }}
      </template>
    </el-table-column>
    <el-table-column prop="mobile" label="电话" sortable width="120px" />
    <el-table-column prop="email" label="邮箱" sortable width="120px" />
    <el-table-column prop="status" label="状态" sortable width="120px">
      <template #default="scope">
        <el-switch
          v-model="scope.row.status"
          active-value="1"
          inactive-value="0"
          @click="switchChange(scope.row)"
        />
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" width="120">
      <template #default="scope">
        <el-button
          type="primary"
          size="small"
          :icon="Edit"
          circle
          @click="editRow(scope)"
        />
        <el-button
          type="danger"
          size="small"
          :icon="Delete"
          circle
          @click="deleteRow(scope)"
        />
      </template>
    </el-table-column>
  </el-table>
  <div class="pagination">
    <el-pagination
      :page-sizes="[2, 5, 20, 40, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      :default-page-size="pagination.size"
      @change="onPaginationChange"
    />
  </div>

  <el-dialog
    class="updateDialog"
    v-model="plusAndEditDialog.isVisible"
    :title="plusAndEditDialog.title"
    align-center
  >
    <el-form label-width="100px" label-position="left">
      <el-form-item label="用户名">
        <el-input v-model="plusAndEditForm.username" />
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="plusAndEditForm.nickname" />
      </el-form-item>
      <el-form-item label="权限">
        <el-input v-model="plusAndEditForm.role" />
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="plusAndEditForm.gender">
          <el-radio value="M"> 男 </el-radio>
          <el-radio value="F"> 女 </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="plusAndEditForm.mobile" />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="plusAndEditForm.email" />
      </el-form-item>
      <el-form-item label="状态">
        <span>禁用&nbsp;</span>
        <el-switch
          v-model="plusAndEditForm.status"
          active-value="1"
          inactive-value="0"
        />
        <span>&nbsp;启用</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <!-- <el-button @click="centerDialogVisible = false">Cancel</el-button> -->
        <el-button type="primary" @click="save"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="less">
.toolbar {
  padding-bottom: 10px;
  display: flex;
}

.filter {
  display: flex;
  margin-bottom: 10px;
}
.el-input,
.el-select {
  max-width: 250px;
}

.pagination {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}
.el-table {
  height: calc(100vh - 265px);
}
.el-form {
  padding: 20px 40px;
}

.favoriteProduct {
  background-color: aqua;
}
</style>
